<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-section">
      <SearchBox 
        v-model="searchKeyword" 
        placeholder="搜索收藏的仓库"
        @search="onSearch"
        @input="onSearchInput"
      />
    </view>
    
    <!-- 收藏列表 -->
    <view v-if="!loading && filteredFavoriteList.length" class="favorite-list">
      <view 
        v-for="(item, idx) in filteredFavoriteList" 
        :key="idx" 
        class="favorite-item"
        :class="{ selected: selectedItems.includes(item.warehouseId) }"
        @click="toggleSelection(item.warehouseId)"
        @longpress="enterSelectionMode(item.warehouseId)"
      >
        <warehourseItem :item="item.warehouse" />
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-section">
      <uni-load-more status="loading" />
    </view>
    
    <!-- 空状态 -->
    <view v-if="!loading && filteredFavoriteList.length === 0" class="empty-section">
      <view class="empty-content">
        <!-- <image src="/static/assets/empty-favorite.png" class="empty-image" mode="aspectFit" /> -->
        <text class="empty-title">{{ searchKeyword ? '未找到相关收藏' : '暂无收藏' }}</text>
        <!-- <text class="empty-desc">{{ searchKeyword ? '试试其他关键词' : '去发现更多优质仓库吧' }}</text>
        <button v-if="!searchKeyword" class="discover-btn" @click="goDiscover">
          去发现
        </button> -->
      </view>
    </view>
    
    <!-- 加载更多 -->
    <view v-if="filteredFavoriteList.length > 0" class="load-more-section">
      <uni-load-more :status="loadMoreStatus" />
    </view>
  </view>
</template>

<script>
import { API } from '@/utils/api.js'
import {warehourseItem} from '@/components/warehourseItem.vue'
import { 
  processImageUrls
} from '@/utils/url-helper.js';
import SearchBox from '@/components/SearchBox.vue'

export default {
  name: "myFavorite",
  components: {
    warehourseItem,
    SearchBox
  },
  data() {
    return {
      favoriteList: [],
      loading: false,
      page: 1,
      pageSize: 10,
      hasMore: true,
      loadMoreStatus: 'more',
      searchKeyword: '',
      selectedItems: [],
      searchTimer: null
    }
  },
  
  onLoad() {
    this.loadFavoriteList();
  },
  
  onPullDownRefresh() {
    this.refreshList();
  },
  
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore();
    }
  },
  
  computed: {
    // 过滤后的收藏列表
    filteredFavoriteList() {
      if (!this.searchKeyword) {
        return this.favoriteList;
      }
      
      const keyword = this.searchKeyword.toLowerCase();
      return this.favoriteList.filter(item => 
        item.warehouseName && item.warehouseName.toLowerCase().includes(keyword) ||
        item.address && item.address.toLowerCase().includes(keyword) ||
        item.warehouseType && item.warehouseType.toLowerCase().includes(keyword)
      );
    }
  },
  
  methods: {
    // 加载收藏列表
    async loadFavoriteList(refresh = false) {
      if (this.loading) return;
      
      try {
        this.loading = true;
        
        if (refresh) {
          this.page = 1;
          this.hasMore = true;
        }
        
        const params = {
          page: this.page,
          pageSize: this.pageSize
        };
        
        const response = await API.favorite.getList(params);
        console.log(response);


        if (response.rows) {          
          if (refresh) {
              this.favoriteList = response.rows;
          } else {
            this.favoriteList = [...this.favoriteList, ...(response.rows || [])];
          }
          this.favoriteList.forEach(item => {
            console.log("item.warehouse", item.warehouse);
            item.warehouse = processImageUrls(item.warehouse);
            console.log("item.warehouse", item.warehouse);
            if(item.warehouse.vrLink && item.warehouse.vrLink.length > 0){
              item.warehouse.warehouseTags = [{
                tagName: 'VR看仓',
                tagImage: '/static/assets/home/home-icon-vr.png',
                tagId: -2
                },...item.warehouse.warehouseTags];
            }
            if(item.warehouse.isRecommend){
              item.warehouse.warehouseTags = [{
                tagName: '推荐',
                tagImage: '/static/assets/home/home-isRecommend.png',
                tagId: -1
              },...item.warehouse.warehouseTags];
            }
          });
          this.hasMore =  this.favoriteList.length < response.total;
          this.loadMoreStatus = this.hasMore ? 'more' : 'noMore';
        }
        
      } catch (error) {
        console.error('获取收藏列表失败:', error);
        uni.showToast({ 
          title: error.message || '获取收藏列表失败', 
          icon: 'none' 
        });
        this.loadMoreStatus = 'more';
      } finally {
        this.loading = false;
        uni.stopPullDownRefresh();
      }
    },
    
    // 刷新列表
    async refreshList() {
      await this.loadFavoriteList(true);
    },
    
    // 加载更多
    async loadMore() {
      if (!this.hasMore || this.loading) return;
      
      this.page += 1;
      await this.loadFavoriteList();
    },
    
    
    // 查看详情
    goDetail(item) {
      if (!item.warehouseId) {
        uni.showToast({ title: '无效的仓库信息', icon: 'none' });
        return;
      }
      uni.navigateTo({ 
        url: `/pages/warehouse/warehouseDetail?id=${item.warehouseId}` 
      });
    },
    
    // 搜索输入
    onSearchInput() {
      // 清除之前的定时器
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }
      
      // 设置新的定时器，300ms后执行搜索
      this.searchTimer = setTimeout(() => {
        this.page = 1; // 搜索时重置页码
        this.hasMore = true; // 搜索时重置加载更多状态
        this.loadMoreStatus = 'more';
        this.loadFavoriteList(true);
      }, 300);
    },

    // 搜索确认
    onSearch() {
      this.page = 1;
      this.hasMore = true;
      this.loadMoreStatus = 'more';
      this.loadFavoriteList(true);
    },

    // 清除搜索
    clearSearch() {
      this.searchKeyword = '';
      this.page = 1;
      this.hasMore = true;
      this.loadMoreStatus = 'more';
      this.loadFavoriteList(true);
    },

    // 切换选择状态
    toggleSelection(warehouseId) {
      const index = this.selectedItems.indexOf(warehouseId);
      if (index > -1) {
        this.selectedItems.splice(index, 1);
      } else {
        this.selectedItems.push(warehouseId);
      }
    },

    // 取消选择所有
    cancelSelection() {
      this.selectedItems = [];
    },

    // 批量取消收藏
    async batchCancelFavorite() {
      if (this.selectedItems.length === 0) {
        uni.showToast({ title: '请选择要取消收藏的仓库', icon: 'none' });
        return;
      }

      try {
        await Promise.all(this.selectedItems.map(warehouseId => API.favorite.cancel({ warehouseId })));
        
        // 从列表中移除
        this.favoriteList = this.favoriteList.filter(item => !this.selectedItems.includes(item.warehouseId));
        
        uni.showToast({ title: '批量取消收藏成功', icon: 'success' });
        
        // 如果列表为空，显示空状态
        if (this.favoriteList.length === 0) {
          this.hasMore = false;
          this.loadMoreStatus = 'noMore';
        }
        
      } catch (error) {
        console.error('批量取消收藏失败:', error);
        uni.showToast({ 
          title: error.message || '批量取消收藏失败', 
          icon: 'none' 
        });
      } finally {
        this.selectedItems = []; // 取消选择所有
      }
    },

    // 进入选择模式
    enterSelectionMode(warehouseId) {
      if (this.selectedItems.length === 0) {
        this.selectedItems.push(warehouseId);
      }
    },

    // 跳转到发现页面
    goDiscover() {
      uni.navigateTo({
        url: '/pages/warehouse/warehouseList'
      });
    }
  }
}
</script>

<style scoped>
.container {
  background: #f5f5f5;
  min-height: 100vh;
  padding: 24rpx 0 100rpx ;
}

.search-section {
  margin-bottom: 24rpx;
  padding: 0 24rpx;
}

.search-bar {
  background: #ffffff;
  border-radius: 20rpx;
  padding: 20rpx 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  border: 1rpx solid #f0f0f0;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  background: #f8f8f8;
  border-radius: 16rpx;
  padding: 16rpx 20rpx;
  border: 1rpx solid transparent;
  transition: all 0.3s ease;
}

.search-input-wrapper:focus-within {
  border-color: #C02C38;
  background: #ffffff;
  box-shadow: 0 0 0 2rpx rgba(192, 44, 56, 0.1);
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  padding-left: 16rpx;
  background: transparent;
}

.search-input::placeholder {
  color: #999;
}

.favorite-list {
  padding: 0;
}

.favorite-item {
  background: #ffffff;
  border-radius: 20rpx;
  margin-bottom: 24rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 2rpx solid transparent;
}

.favorite-item:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.12);
}

.favorite-item.selected {
  border-color: #C02C38;
  background: #fff8f8;
  box-shadow: 0 4rpx 20rpx rgba(192, 44, 56, 0.15);
}

.loading-section {
  margin: 40rpx 0;
  text-align: center;
}

.empty-section {
  margin: 80rpx 0;
  text-align: center;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #ffffff;
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
  opacity: 0.7;
}

.empty-title {
  margin-bottom: 16rpx;
  font-size: 32rpx;
  color: #666;
  font-weight: 500;
}

.empty-desc {
  font-size: 26rpx;
  color: #999;
  line-height: 1.5;
}

.discover-btn {
  margin-top: 40rpx;
  padding: 20rpx 48rpx;
  border-radius: 24rpx;
  background: linear-gradient(135deg, #C02C38 0%, #e74c3c 100%);
  color: #ffffff;
  font-size: 28rpx;
  font-weight: 600;
  border: none;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 16rpx rgba(192, 44, 56, 0.3);
}

.discover-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2rpx 8rpx rgba(192, 44, 56, 0.4);
}

.load-more-section {
  margin: 40rpx 0;
  text-align: center;
}
</style>